package com.ch.engine.utils;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Objects;

/**
 * VcExcel工具
 *
 * @author zh
 * @date 2022/5/10 17:59
 */
@Slf4j
public class VcExcelUtil {

    public static final String UTF8 = "UTF-8";
    public static final String CONTENT_DISPOSITION = "Content-disposition";
    public static final String APPLICATION_EXCEL = "application/vnd.ms-excel";
    public static final String HEADER = "attachment;filename=%s";

    private VcExcelUtil() {
    }

    /**
     * 导出模板Excel
     *
     * @param inputStream         模板对应输出
     * @param downLoadBusinessDTO 导入模板
     * @param fileName            导出文件名称
     * @param response            HttpServletResponse
     * @author hfq
     */
    public static void downloadExcel(InputStream inputStream, Object downLoadBusinessDTO, String fileName, HttpServletResponse response) {
        ExcelWriter excelWriter = null;
        try {
            ServletOutputStream out = response.getOutputStream();
            //设置文件类型
            response.setContentType(APPLICATION_EXCEL);
            //设置编码格式
            response.setCharacterEncoding(UTF8);
            response.setHeader(CONTENT_DISPOSITION, String.format(HEADER, URLEncoder.encode(fileName, StandardCharsets.UTF_8)));

            //创建excel
            excelWriter = EasyExcel.write(response.getOutputStream()).withTemplate(inputStream).build();
            // 创建sheet
            WriteSheet writeSheet = EasyExcel.writerSheet().build();
            excelWriter.fill(downLoadBusinessDTO, writeSheet);
            out.flush();
        } catch (IOException e) {
            log.error("downloadExcel 下载模板出错！", e);
//            throw new CommonException(ResultCode.DOWNLOAD_IS_ERROR);
        } finally {
            if (Objects.nonNull(excelWriter)) {
                excelWriter.finish();
            }
        }
    }
}
